<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="c_index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" :clearable='false')
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" :clearable='false')
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            //- .table-title-lefttxt.pull-left
            //-   |合计
            //-   span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
            //-   |条
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasExport" type="info" @click="exportApply") 导出
          .clearfix.pl-20.pr-20(slot="footer")
            //- Page(
            //-   :total="tableComone.totalRows"
            //-   @on-change="onChangePage"
            //-   @on-page-size-change="onpageSizeChange"
            //-   show-sizer
            //-   show-total
            //-   placement="top"
            //-   prev-text="上一页"
            //-   next-text="下一页"
            //-   :page-size-opts="[10, 20, 30, 50, 100]"
            //- )

</template>

<script>
import { Common } from '@/utils/common.js'
import { FinancePayAccountApi } from '@/api/FinancePayAccount.api.js'
import { FinanceSPayableApi } from '@/api/FinanceSPayable.api.js'
import { ManageDataAnalysisThead } from '../tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import { ManageDataAnalysisApi } from '@/api/ManageDataAnalysis.api.js'
import moment from 'moment'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'manageDataAnalysis',

  components: {
  },

  data () {
    return {
      thead: _cloneDeep(ManageDataAnalysisThead),
      tableData: [],
      formData: {
        startDate: this.$moment(new Date()).format('YYYY-MM'),
        endDate: this.$moment(new Date()).format('YYYY-MM')
      },
      formItem: [
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-4' }
      ],
      rules: {
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: [],
        status: [
        ],
        payAccount: [],
        PayType: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      isDelete: false
    }
  },

  watch: {
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    
  },

  mounted () {
    this.getEnum()
    this.getEnum2()
    this.query()
  },

  methods: {
    getEnum () {
      let typeName = 'PayType'
      Common.getSelectIdList(typeName, this.arrListDown)
    },

    // 数据字典
    getEnum2 () {
      let groupName = 'financesalary.status'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        ...this.formData,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):'',
      }
      let res = await ManageDataAnalysisApi.find(params)
      console.log('薪资付款申请res: ', res)
      console.log('ManageDataAnalysisThead', ManageDataAnalysisThead)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        for ( let i in ManageDataAnalysisThead) {
          if (ManageDataAnalysisThead[i].key == 'billVerifyTotal' || ManageDataAnalysisThead[i].key == 'invoiceDateTotal') {
            let childs = []
            let keyArr = JSON.parse(JSON.stringify(this.tableData[0][ManageDataAnalysisThead[i].key]))
            for (let j in keyArr) {
              if (keyArr[j].title){
                console.log(ManageDataAnalysisThead[i].key+''+j,'k-j')
                childs.push({
                  title: keyArr[j].title,
                  key: ManageDataAnalysisThead[i].key+''+j,
                  minWidth: 100,
                  align: 'center'
                })
              }
            }
            console.log(childs,'childs')
            ManageDataAnalysisThead[i].children=childs
          }
        }

        for (let i in this.tableData) {
          this.tableData[i].billInvoiceCount += '%' 
          this.tableData[i].forthWithInvoiceCount += '%' 
          this.tableData[i].noInvoiceCount += '%' 
          for (let j in this.tableData[i].invoiceDateTotal) {
            this.tableData[i]['invoiceDateTotal'+ j] = this.tableData[i].invoiceDateTotal[j].curCount+'%'
          }
          for (let k in this.tableData[i].billVerifyTotal) {
            this.tableData[i]['billVerifyTotal'+ k] = this.tableData[i].billVerifyTotal[k].curCount+'%'
          }
        }
        console.log(this.tableData,'this.tableData')
        this.thead= _cloneDeep(ManageDataAnalysisThead)
        this.tableData = this.tableData
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
    },

    // 导出薪资付款申请
    async exportApply () {
      var params = {
        ...this.formData,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):''
      }
      let res = await ManageDataAnalysisApi.export(params)
      console.log('导出管理数据分析res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },


  } // methods end
}
</script>

<style lang="less" scoped>

</style>
